<?php
class helper_cache extends system_view_cache {
	
	/**
	 * @return helper_cache
	 */
	public function cache() {
		return $this;
	}

	public function __call($method, $args) {
		if(!preg_match('/^get(\w+?)$/', $method, $matches)) {
			$element = $this->getView()->getHelper('cache_' . $method);
			return call_user_func_array(array($element, $method), $args);
		}
		return parent::__call($method, $args);
	}


	public function categories() {
		$result = array();
		$concept = new picture_category_concept($this->lang);
		foreach($concept->fetchAll(array("locale.is_active = 1"), 'locale.display_order ASC')->toArray() AS $key => $row) {
			$result[$key] = $row;
			$result[$key]['_url'] = $this->url('category/index', array('name' => $row['name']));
			$result[$key]['_cover'] = $this->image($row['cover']);
		}
		return $result;
	}
	
	public function category_tree($pid = null) {
		picture_category::$_lang = $this->lang;
		return picture_category::allCategoryToTreeAsArray();
	}
	
	public function keywords($args = array()) {
		$limit = isset($args['limit']) ? $args['limit'] : 10;
		$orderby = array('hit_total', 'hit_day', 'hit_week', 'hit_month');
		$orderIndex = $orderby[rand(0, count($orderby) - 1)];
		$concept = new resource_keyword_concept($this->lang);
		$sql1 = "SELECT `keyword_id` FROM `picture_special_keyword` WHERE `special_id` IN(
				SELECT a.`id` FROM `picture_special` AS a INNER JOIN `picture_special_locale` AS b
				ON a.`id` = b.`special_id`
				WHERE a.`is_active` = '1' AND b.`lang` = '{$this->lang}')";
		$sql2 = "SELECT `keyword_id` FROM `picture_photo_keyword` WHERE `photo_id` IN(
				SELECT a.`id` FROM `picture_photo` AS a INNER JOIN `picture_photo_locale` AS b
				ON a.`id` = b.`photo_id`
				WHERE a.`is_active` = 1 AND b.`lang` = '{$this->lang}')";
		$result = array();
		foreach($concept->fetchAll("id IN($sql1) OR id IN($sql2)", array("$orderIndex DESC"), $limit)->toArray() AS $key => $row) {
			$result[$key] = $row;
			$result[$key]['_url'] = $this->url('search/keyword', array('name' => $row['name']));
		}
		return $result;
	}
	
	public function oauth_row(array $args) {
		$lang = $args['lang'];
		$source = $args['source'];
		$uid = $args['uid'];
		
		$concept = new community_oauth_concept();
		if(!($row = $concept->fetch(array('source_id = ?' => $source, 'passport_id = ?' => $uid)))) {
			$row = $concept->fetch(array('source_id = ?' => $source, 'passport_id = ?' => $this->default[$lang]['uid']));
		}
		if(!$row) {
			$row = $concept->create();
			$row->setSourceId($source);
		}
		return $row;
	}
	
}
